﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RayTracing : MonoBehaviour {

	public ViewPlane vp;

	public Renderer render;

	public float zw = 100.0f;

	Color backgroundColor = Color.black;

	List<Ray> rayList = new List<Ray>();


	void Start () {

		//根据ViewPlane的本身大小（在Unity中的物理大小（unity单位）和像素大小和ViewPlane中的像素大小得到图片的size（二维）
		Debug.LogFormat("目标图像分辨率(宽X高）: {0} X {1}", vp.HRes, vp.VRes);


		//生成相应的Texture2D，用来显示
		Texture2D texture = new Texture2D(vp.HRes, vp.VRes, TextureFormat.ARGB32, false);
		texture.filterMode = FilterMode.Point;

		for (int r = 0; r <= vp.VRes; ++r) {
			for (int c = 0; c <= vp.HRes; ++c) {
				//取到书中的所有的白色点的位置
				Vector2 rayStart = vp.GetPoint(c, r);
				Debug.LogFormat ("the ray start is: {0} {1}", rayStart.x, rayStart.y);

				//射线，从ViewPlane上的点出发，往+z方向延伸
				float x = rayStart.x, y = rayStart.y;
				Vector3 origin = new Vector3(x, y, vp.transform.position.z);
				Vector3 direction = new Vector3 (x, y, vp.transform.position.z + zw);

				Ray ray = new Ray (origin, direction);

				rayList.Add (ray);

				//ray和场景的交互（取到击中点，根据光照得到色值，这里我们可以使用Unity的场景功能）
				RaycastHit hitInfo;
				if (Physics.Raycast (ray, out hitInfo, 1000f)) {
					Debug.Log ("Hit a position");

					//取色
					Color color = GetColor (hitInfo);

					//
					texture.SetPixel (c, r, color);
				} else {
					texture.SetPixel (c, r, backgroundColor);
				}
			}
		}

		//
		texture.Apply();

		render.material.mainTexture = texture;
	}

	void OnDrawGizmos() {

		Gizmos.color = Color.red;

		for (int i = 0; i < rayList.Count; ++i) {
			Ray ray = rayList [i];
			Gizmos.DrawRay (ray);
		}
	}

	Color GetColor(RaycastHit hitInfo) {
		//最简单的是直接取一个色，复杂的就需要shoot出更多的射线
//		return Color.red;

		//材质

		//光照
		Vector3 lightDir = GameObject.Find("Directional Light").transform.TransformDirection(Vector3.back);

		//1, Lambertian diffuse model
		Color result = Color.red * Color.white * Vector3.Dot(lightDir, hitInfo.normal);
		return result;
	}
}
